<template>  
    <HeaderComponent /> <!-- 顶部导航栏 -->
      <div id="BackLink">
      <router-link to="/main">Return to Main Menu</router-link>
      </div>

    
      <div id="Catalog">
      <div id="cart">
        <h2>Shopping Cart</h2>
  
        <form @submit.prevent="updateCart">
          <table>
            <thead>
              <tr>
                <th>Item ID</th>
                <th>Product ID</th>
                <th>Description</th>
                <th>In Stock?</th>
                <th>Quantity</th>
                <th>List Price</th>
                <th>Total Cost</th>
                <th>&nbsp;</th>
              </tr>
            </thead>
            <tbody>
              <tr v-if="cartItems.length === 0">
                <td colspan="8"><b>Your cart is empty.</b></td>
              </tr>
              <tr v-for="cartItem in cartItems" :key="cartItem.itemId">
                <td>
                  <router-link :to="`/item/${cartItem.itemId}`">{{ cartItem.itemId }}</router-link>
                </td>
                <td>{{ cartItem.item.productId }}</td>
                <td>
                 {{(cartItem.item.attribute1) }}
                </td>
                <td>{{ cartItem.inStock ? "Yes" : "No" }}</td>
                <td>
                  <input type="number" v-model="cartItem.number" @input="updateSubTotal" @change="updateCart(cartItem.itemId)" :min="1">
                </td>
                <td>{{ formatCurrency(cartItem.item.listPrice) }}</td>
                <td>{{ formatCurrency(cartItem.number * cartItem.item.listPrice) }}</td>
                <td>
                  <button @click="removeItem(cartItem.itemId)" class="Button">Remove</button>
                </td>
              </tr>
              <tr>
                <td colspan="4">Total:</td>
                <td>{{ formatCurrency(subTotal) }}</td>
              </tr>
              <tr v-if="selectedCouponId">
                <td colspan="4">Discounted Total:</td>
                <td colspan="3" style="color: green;">
                  {{ formatCurrency(finalTotal) }}
                </td>
              </tr>
            </tbody>
          </table>
        </form>
  
        <div v-if="couponList && couponList.length > 0">
          <h2>Available Coupons</h2>
          <table>
            <thead>
              <tr>
                <th>Coupon ID</th>
                <th>Limit</th>
                <th>Deduction</th>
                <th>Discount</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              <tr v-if="couponList.length === 0">
              <td colspan="5"><b>Your coupon package is empty.</b></td>
            </tr>
            <tr v-for="coupon in couponList" :key="coupon.id">
              <template v-if="subTotal >= coupon.limit">
                <td>{{ coupon.id }}</td>
                <td>{{ coupon.limit }}</td>
                <td>{{ coupon.deduction }}</td>
                <td>{{ coupon.discount }}</td>
                <td>
                  <input type="radio" name="selectCoupon" :value="coupon.id" v-model="selectedCouponId"> Yes
                </td>
              </template>
            </tr>
            <tr v-if="couponList.length > 0 && !couponList.some(c => subTotal >= c.limit)">
              <td colspan="5">No available coupons. You can purchase more to reach the lower limit of the coupon.</td>
            </tr>
            </tbody>
          </table>
        </div>
  
        <button @click="checkout" :disabled="cartItems.length === 0">Proceed to Checkout</button>
      </div>
  
   
    </div>

  </template>
  
  <script setup>
import { ref, computed, onMounted } from 'vue';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import { getCart, updateCartItem, removeCartItem, getCoupons } from '@/api/cart.js';
import { getItemDetails } from '@/api/item.js'; 
import HeaderComponent from '@/components/Header.vue';
import FooterComponent from '@/components/Footer.vue';
import "@/assets/css/global.css";

// Vuex 和 Router 实例
const store = useStore();
const router = useRouter();

// 响应式数据
const cartItems = ref([]);
const couponList = ref([]);
const subTotal = ref(0);

const selectedCouponId = ref(null);

// 计算属性：从 Vuex 中读取 loginAccount
//const loginAccount = computed(() => store.state.loginAccount);

// 获取购物车数据
const fetchCartData = async () => {
  try{const token = localStorage.getItem('token');
  const response = await getCart(token); // 改写 getCart 方法，支持传 token
  cartItems.value = response.data.cartItems;
  subTotal.value = response.data.total;

  const couponsResponse = await getCoupons(token); // 改写 getCoupons 方法，支持传 token ,await getCoupons(token)
  couponList.value = couponsResponse.data; // 传入 token
  console.log("购物车:",cartItems.value);
  console.log("优惠券：",couponList.value);
  }catch (error) {
    console.error("fetchCartData 错误:", error);
  }

};

// 新增方法：实时更新 subTotal
const updateSubTotal = () => {
  subTotal.value = cartItems.value.reduce((total, item) => {
    return total + item.number * item.item.listPrice;
  }, 0);
};


// 修改购物车
const updateCart = async (itemId) => {
  const cartItem = cartItems.value.find(item => item.itemId === itemId);
  await updateCartItem(itemId, cartItem.number);
  fetchCartData();
};

// 删除购物项
const removeItem = async (itemId) => {
  await removeCartItem(itemId);
  fetchCartData();
};

// 去结算
const checkout = () => {
  router.push({ path: '/checkout', query: { username: localStorage.getItem('username') ,couponId: selectedCouponId.value } });
};

// 获取产品名称（假设产品信息映射存在）
//const products = {}; 
const getProductName = async (productId) => {
  const response = await getItemDetails(productId);
  return response.data.productName;
  //return products[productId] ? products[productId].productName : 'Unknown Product';
};

// 价格格式化
const formatCurrency = (amount) => {
  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD',
  }).format(amount);
};

// 计算最终价格
const finalTotal = computed(() => {
  const coupon = couponList.value.find(c => c.id === selectedCouponId.value);
  if (!coupon || subTotal.value < coupon.limit) return subTotal.value;

  // 优先使用满减
  if (coupon.deduction > 0) {
    return Math.max(subTotal.value - coupon.deduction, 0);
  }

  // 使用折扣
  if (coupon.discount > 0) {
    return subTotal.value * coupon.discount;
  }

  return subTotal.value;
});

// 生命周期钩子
onMounted(() => {
  fetchCartData();
});
</script>
<style scoped>  
/* 按钮正常状态 */
Button, Button:link, Button:visited {
    padding: .3ex 1ex; /* 调整内边距 */
    color: #734012; /* 深棕色文字，与主色调一致 */
    background-color: #fccc1c; /* 亮黄色背景，与主色调一致 */
    text-decoration: none; /* 去掉下划线 */
    font-family: helvetica, tahoma, arial, verdana, sans-serif; /* 字体 */
    font-size: 1.5ex; /* 字体大小 */
    /* border: 2px solid #734012;深棕色边框 */
    border-radius: 6px; /* 圆角 */
    transition: all 0.3s ease; /* 平滑过渡效果 */
}

/* 按钮悬停状态 */
Button:hover {
    color: #fff; /* 白色文字 */
    background-color: #734012; /* 深棕色背景 */
    border-color: #734012; /* 保持深棕色边框 */
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* 添加阴影效果 */
}

/* 按钮按下状态 */
Button:active {
    background-color: #b3741d; /* 较深的橙色背景 */
    color: #fff; /* 保持白色文字 */
    box-shadow: inset 0 4px 6px rgba(0, 0, 0, 0.3); /* 内嵌阴影，增加按压感 */
}
</style>